<?
class DatabaseException extends Exception {}

class DB
{

	public function __construct($server, $db_name, $user, $pass)
	{
		mysql_connect($server, $user, $pass) or die('Server connection not possible.');
		mysql_select_db($db_name) or die('Database connection not possible.');
	}

	public function query($query)
	{
		return mysql_query($query) or $this->error($query);
	}
	
	/**
	* For queries with no return value (inserts, etc)
	*/
	public function execute($query)
	{
		mysql_query($query) or $this->error($query);
	}

	/**
	*  Returns all results as an array which can be foreach'd
	*/
	public function get_all($query)
	{
		$return=array();
		$result=mysql_query($query) or $this->error($query);
		while($row=mysql_fetch_assoc($result))
		{
			$return[] = $row;
		}
		return $return;
	}
	
	/**
	* Returns the first row
	*/
	public function get_row($query)
	{
		$result = mysql_query($query) or $this->error($query);
		return mysql_fetch_assoc($result);
	}
	
	/**
	* Returns the value of the first cell
	*/
	public function get_one($query)
	{
		$result = mysql_query($query) or $this->error($query);
		$line = mysql_fetch_row($result);
		return $line[0];
	}
	
	/**
	* returns a description of a fields in a table
	*/
	public function describe($table)
	{
		$query="SHOW COLUMNS FROM $table";
		$return=array();
		$result = mysql_query($query) or $this->error($query);
		while($row=mysql_fetch_assoc($result))
		{
			$return[$row['Field']] = $row;
		}
		return $return;
		
	}
	
	public function count($query)
	{
		return $this->get_one("SELECT COUNT(q.*) FROM ($query) as q");
	}
	
	public function last_inserted_id()
	{
		return mysql_insert_id();
	}

	private function error($query="")
	{
		$error_message = "MySQL Error: ". mysql_error();
		if ($query) $error_message .="\n\n Query:  $query";
		throw new DatabaseException($error_message);
	}

	public function sanitize($value)
	{
		if (get_magic_quotes_gpc())
		{
	        $value = stripslashes($value);
	    }
		return mysql_real_escape_string($value);
	}
}
?>